/*
 * @Author: hcluo
 * @Date: 2020-08-29 10:41:54
 * @LastEditors: hcluo
 * @LastEditTime: 2020-08-29 11:07:33
 * @Description:
 */
import { useCallback, useState, useEffect } from 'react';

const doRequest = fetch;
export function useRequest(url = './', getParams, deps) {
  const [status, setStatus] = useState(typeof getParams === 'function' ? 1 : 0); // 0-已完成，1-发送中，2-返回出错
  const [data, setData] = useState([]);
  const [errorMsg, setErrorMsg] = useState();
  const boundAction = useCallback(() => {
    setStatus(1);
    doRequest(url)
      .then(response => {
        if (!response.ok) {
          return Promise.reject(response.status);
        }
        return response.json();
      })
      .then(res => {
        setData(res);
        setStatus(0);
      })
      .catch(err => {
        console.error('%c 🥒 err: ', 'font-size:20px;background-color: #FCA650;color:#fff;', err);
        setErrorMsg(err);
        setStatus(2);
      });
  }, [url]);
  useEffect(() => {
    boundAction();
    // if (typeof getParams === 'function') {
    //   let params = getParams();
    //   params && boundAction(getParams());
    // }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  return [data, status, boundAction, errorMsg];
}
